<?php (defined('BASEPATH')) OR exit('No direct script access allowed');

class User_Model extends CI_Model {
	
	private $table= 'users';
	private $regular_hours = 8;
	function __construct() {
		parent::__construct();
		$this->clientModel = $this->load->model('Client_Model'); 
		$this->dbGeneric = $this->load->model('Dbgeneric_Model'); 
		$this->load->helper('CommonUtils');
	}
	
	function login ($username, $password){
		$password = CommonUtils::encryptPassword($password);
		
		$this->db->select("u.*, r.name as role_name, c.name as client_name, c.api as client_api, c.code as client_code");
		$this->db->from('users as u');
		$this->db->join('role as r','u.role = r.id','left');
		$this->db->join('clients as c','u.client_id = c.id', 'left');
		$this->db->where('u.username',$username);
		$this->db->where('u.password',$password);
		$this->db->where('u.is_active',1);
		$query = $this->db->get();
		$result = $query->result();
    	//$query = $this->db->get_where($this->table, array('username' => $username,'password'=>$password, 'is_active'=>1));
    	return $result;
	}
	
	function save($data){
		$this->db->insert($this->table, $data);
		return $this->db->insert_id();
	}
	
	function isClientAllowed($clientId, $userId) {
		$query = $this->db->get_where($this->table, array('id' => $userId,'client_id'=>$clientId));
    	$result = $query->result();
    	return !empty($result);
	}
	
	/*function getAllUsers(){
		$query = $this->db->get('users');
		return $query->result();
	}*/
	
	function getAllUsers($api){
		//$query = $this->db->get('users');
		//return $query->result();
		$client = $this->clientModel->find($api);
		
		//var_dump($client);
		$this->db->select('u.*, f.first_name, f.middle_name, f.last_name');
		$this->db->from('users as u');
		$this->db->join('file201 as f','f.user_id = u.id','left');
		$this->db->where('u.client_id', $client->id);
		$query = $this->db->get();
		return $query->result();
	}
	
	function saveOrUpdateData($table, $data, $user_id = 0){
		//
		if(isset($data['user_id'])){
			unset($data['user_id']);
		}
		if($user_id > 0) {
			$this->db->where('user_id', $user_id);
			$this->db->update($table, $data);
			return true;
		} else {
			$this->db->insert($table, $data);
			return $this->db->insert_id();
		}
	}
	
	function find($array){
		$query = $this->db->get_where($this->table, $array);
    	$result = $query->result();
    	return $result;
	}
	
	function saveEducation($schools,$date_start,$date_end,$type,$ids,$user_id){
		$cnt = 0;
		foreach ($schools as $school){
			$item = array();
			$item['school_name'] = trim($school);
			$item['date_start'] = $date_start[$cnt];
			$item['date_end'] = $date_end[$cnt];
			$item['type'] = $type[$cnt];
			$item['user_id'] = $user_id;
			$id = $ids[$cnt];
			if($id <= 0 && ($item['school_name'] != ""))
				$this->saveData('education',$item);
			else {
				$this->db->where('id', $id);
				$this->db->update('education', $item); 
			}
			$cnt++;
		}
		
		return true;
	}
	
	function getUserProfile($api, $user_id){
		$client = $this->clientModel->find($api);
		if($this->isClientAllowed($client->id, $user_id)) {
			$query = $this->db->get_where('file201', array('user_id' => $user_id));
			$result = $query->result();
			return $result;
		} else 
		return false;
		
	}
	
	function getDependents($api, $user_id){
		$client = $this->clientModel->find($api);
		if($this->isClientAllowed($client->id, $user_id)) {
			$query = $this->db->get_where('dependents', array('user_id' => $user_id));
			$result = $query->result();
			return $result;
		} else 
		return false;
	}
	
	function getEmployment($api, $user_id){
		$client = $this->clientModel->find($api);
		if($this->isClientAllowed($client->id, $user_id)) {
			$query = $this->db->get_where('employment', array('user_id' => $user_id));
			$result = $query->result();
			return $result;
		} else 
		return false;
	}
	
	function getUserSalary($api, $user_id){
		$client = $this->clientModel->find($api);
		if($this->isClientAllowed($client->id, $user_id)) {
			$query = $this->db->get_where('salary', array('user_id' => $user_id));
			$result = $query->result();
			return $result;
		} else 
		return false;
	}
	
	function uploadPicture($api, $params){
		$client = $this->clientModel->find($api);
		if($this->isClientAllowed($client->id, $params['user_id'])) {
			if(isset($params['photo']) && isset($params['user_id'])) {
				$item = array('photo'=>$params['photo']);
				$this->db->where('user_id', $params['user_id']);
				$this->db->update('file201', $item);
			}
			
			return true;
		} else 
		return false;
	}
	
	function getUserRestDay($api, $user_id){
		$client = $this->clientModel->find($api);
		if($this->isClientAllowed($client->id, $user_id)) {
			$query = $this->db->get_where('user_rest_day', array('user_id' => $user_id));
			$result = $query->result();
			return $result;
		} else 
		return false;
	}
	
	function isUserRestDay($api, $user_id, $date){
		$client = $this->clientModel->find($api);
		$day = strtolower(date('l', strtotime($date)));
		//echo $day;
		if(is_numeric($user_id)) {
			$query = $this->db->get_where('user_rest_day', array('user_id' => $user_id, 'day'=>$day));
			$result = $query->result();
			return $result;
		} else 
		return false;
	}
	
	function getUserRate($user_id , $type='object'){
		if(is_numeric($user_id)) {
			$query = $this->db->get_where('user_rates', array('user_id' => $user_id));
			if($type == 'object'){
				$result = $query->result();
			}
			else if($type == 'array') {
				$result = $query->result_array();
			}
			return $result;
		} else 
		return false;
	}
	
	public function getAllRates($api, $user_id){
		$client = $this->clientModel->find($api);
		if($this->isClientAllowed($client->id, $user_id)) {
			if(is_numeric($user_id)) {
				$query = $this->db->get_where('user_rates', array('user_id' => $user_id));
				$result = $query->result();
				return $result;
			} else 
			return false;
		} else 
		return false;
	}
	
	public function getContributions($api,$user_id){
		$client = $this->clientModel->find($api);
		if($this->isClientAllowed($client->id, $user_id)) {
			if(is_numeric($user_id)) {
				$this->db->select('ct.name,ct.key, uc.employee, uc.employer');
				$this->db->from('contribution_type as ct');
				$this->db->join('user_contributions as uc','uc.contribution_type_id = ct.id','left');
				$this->db->where('uc.user_id', $user_id);
				$query = $this->db->get();
				$results = $query->result();
				if(!empty($results)){
					$data = array();
					$total = 0.00;
					foreach($results as $res){
						$total += $res->employee;
						$data[strtolower($res->key)] = array('employee'=>$res->employee,'employer'=>$res->employer);
					}
					$data['total_deductions'] = CommonUtils::number_format($total,2);
					return $data;
				}
			} else 
			return false;
		} else 
		return false;
	}
	
	public function saveOrUpdateUserRates($user_id){
		//echo $user_id;
		$salary = $this->dbGeneric->find('salary',array('user_id'=>$user_id));
		$base_salary = $this->dbGeneric->find('salary_standard', array('id' => 1));
		$base_salary = $this->db->query("Select * from `salary_standard` WHERE id=1")->result_array();
		if(!empty($salary)){
			$daily_rate = $salary[0]->daily / $this->regular_hours;
			if($daily_rate) {
				$fields = $this->db->list_fields('user_rates');
				$exclude = array('id','user_id','adjustment','incentives');
				foreach($fields as $f){
 					if(!in_array($f, $exclude)) {
 						$rate = isset($base_salary[0]["$f"])? $base_salary[0]["$f"]:0;
 						$data["$f"] = $daily_rate * $rate;
 					}
 				}
				$data['user_id'] = $user_id;
				$this->dbGeneric->saveOrUpdate('user_rates',$data,'user_id');
			}
		}

	}
	
	public function saveContributions($data){
		if(!empty($data)){
			$user_id = $data->user_id;
			foreach($data as $key=>$value){
				if($key == "user_id") continue;
				$contr = $this->dbGeneric->find('contribution_type', array('key'=>$key));
				//return  $contr[0]->id;
				if(!empty($contr)) {
					$contr_id = $contr[0]->id;
					$params = array();
					$params["contribution_type_id"] = $contr_id;
					$params["employee"] = $value;
					$params["user_id"] = $user_id;
					$id = $this->dbGeneric->saveOrUpdateArray('user_contributions',$params,array('contribution_type_id','user_id'));
				
				}
				
			}
		}
	}
	
	/*public function getContributions($api,$user_id){
		$client = $this->clientModel->find($api);
		$allowed = $this->isClientAllowed($client->id, $user_id);
		if($allowed){
			$this->db->select('uc.*, ct.key, ct.name');
			$this->db->from('user_contributions as uc');
			$this->db->join('contribution_type as ct','ct.id = uc.contribution_type_id','left');
			$this->db->where('uc.user_id', $user_id);	
			$query = $this->db->get();
			return $query->result();
		}
	}*/
}